import os
import yaml
from datetime import datetime
from components.c_config import app_config

def delete_logs_if_debug():
    if app_config.app_status == 'debug':
        log_dir = app_config.log_dir
        
        if not log_dir.endswith('/'):
            log_dir += '/'
            
        if os.path.exists(log_dir):
            for filename in os.listdir(log_dir):
                file_path = os.path.join(log_dir, filename)
                if os.path.isfile(file_path) and filename.endswith('.log'):
                    os.remove(file_path)
                    print(f"Deleted log file: {file_path}")
        else:
            print(f"Log directory does not exist: {log_dir}")
    else:
        print("Not in debug mode, skipping log deletion.")


def LOG(TAG, *args):
    """支持多参数的日志记录方法
    参数格式: LOG(TAG, arg1, arg2, ...)
    示例: LOG("SportRecordServer", "提交成功", "耗时", 200, "ms")
    """
    # 将多个参数转换为字符串并用空格连接
    message = ' '.join(map(str, args))
    
    # 使用更安全的路径拼接方式
    log_filename = f"{TAG}.log"
    log_path = os.path.join(app_config.log_dir, log_filename)
    
    if log_path:
        with open(log_path, 'a', encoding='utf-8') as file:
            file.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {TAG}: {message}\n")

    # 控制台输出保留原始格式
    print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {TAG}:", *args)

# 使用示例
if __name__ == "__main__":
    # 测试多参数日志
    LOG("System", "服务启动", "版本号", "v2.3.1")
    LOG("Network", "收到请求", "来自IP:", "192.168.1.100", "状态码:", 200)
    
    # 测试混合类型参数
    LOG("Performance", "查询耗时", 245, "ms", "内存使用:", 1024.5, "MB")
    
    # 原始调用方式仍然有效
    LOG("Error", "数据库连接失败")